package com.zzyl.job;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.DeviceDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ffk
 * @date 2024/5/28 21:11
 */

@Slf4j
@Component
public class AlertJob {

    @Autowired
    AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    AlertRuleService alertRuleService;

    @Scheduled(cron = "0/10 * * * * * ")
    public void deviceDataAlertFilter() {
        log.info("真的开始进行报警检查了");

       //查询所有规则
        List<AlertRule> alertRules = alertRuleMapper.selectByFunctionId(null, null, null);

        //为空
        if(CollectionUtils.isEmpty(alertRules)){
            return;
        }

        //非空，从Redis缓存中获取存储在键CacheConstants.IOT_DEVICE_LAST_DATA_KEY下的哈希表的所有值

        List<Object> jsonStrList = redisTemplate.opsForHash().values((CacheConstants.IOT_DEVICE_LAST_DATA_KEY));
        if(CollectionUtils.isEmpty(jsonStrList)){
            return;
        }

        //数据非空，提取

        List<DeviceDataVo> deviceDataList=new ArrayList<>();

        jsonStrList.forEach(json -> deviceDataList.addAll(
                JSONUtil.toList(json.toString(), DeviceDataVo.class)));


        //校验数据
        deviceDataList.forEach(d -> alertRuleService.alertFilter(d));
    }

}
